<?php
// +----------------------------------------------------------------------
// | Tplay [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://tplay.pengyichen.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 听雨 < 389625819@qq.com >
// +----------------------------------------------------------------------


namespace app\admin\controller;

use \think\Db;
use app\admin\model\Order as OrderModel;//商户信息模型
use app\admin\model\OrderGoods as OrderGoodsModel;//商户信息模型
class Order extends Permissions
{
    /**
     * 商户信息列表
     * @return [type] [description]
     */
    public function index()
    {
        //实例化商户信息模型
        $model = new OrderModel();

        $post = $this->request->param();
        if (isset($post['goods_title']) and !empty($post['goods_title'])) {
            $where['order.goods_title'] = ['like', '%' . $post['goods_title'] . '%'];
        }
        if (isset($post['order_status']) and !empty($post['order_status'])) {
            $where['order.order_status'] = ['like', '%' . $post['order_status'] . '%'];
        }
        if (isset($post['pay_status']) and !empty($post['pay_status'])) {
            $where['order.pay_status'] = ['like', '%' . $post['pay_status'] . '%'];
        }
        $admin = empty($where) ? $model->join('user', 'user.id = order.user_id')->field('order.*,user.username')->order('order.create_time desc')->paginate(20) : $model->join('user', 'user.id = order.user_id')->where($where)->order('order.create_time desc')->field('order.*,user.username')->paginate(20, false, ['query' => $this->request->param()]);
        $this->assign('admin', $admin);
        $this->assign('post', $post);
        return $this->fetch();
    }


    /**
     * 商户信息的添加及修改
     * @return [type] [description]
     */
    public function detail()
    {
        //获取商户信息id
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $model = new OrderModel();
        $goodsOrder = new OrderGoodsModel();
        if ($id > 0) {
            //非提交操作
            $info = $model->join('user', 'user.id = order.user_id')->field('order.*,user.username')->where('order.id', $id)->find();
            $info['detail'] = $goodsOrder->where('order_no', $info['order_no'])->select();

            $this->assign('order', $info);
            return $this->fetch();

        } else {
            return $this->error('获取信息失败');
            //非提交操作
//            return $this->fetch();
        }

    }

    /**
     * 修改密码
     * @return [type] [description]
     */
    public function send_goods()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;

        if ($id > 0) {
            if ($this->request->isPost()) {
                $post = $this->request->post();
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['express_company', 'require', '物流公司不能为空'],
                    ['express_no', 'require', '物流单号不能为空'],
                    ['express_id', 'require', '物流id不能为空'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }
                $post['delivery_time'] = time();
                $post['order_status'] = 40;

                if (false == Db::name('order')->where('id', $id)->update($post)) {
                    return $this->error('发货失败');
                } else {
                    //发货成功后需要调用微信小程序发货订单数据
                    $order_data = Db::name('order')->where('id', $id)->limit(1)->find();
                    if ($order_data) {
                        $user = \app\admin\model\User::where('id', $order_data['user_id'])->limit(1)->find();
                    }
                    $this->uploadWxappShippingInfo($user['openid'], $order_data);
                        addlog();//写入日志
                    return $this->success('发货成功');
                }

            } else {
                $id = $id;
                $express = Db::name('express')->select();
                $this->assign('id', $id);
                $this->assign('express', $express);
                return $this->fetch();
            }
        } else {
            $id = $id;
            $this->assign('id', $id);
            return $this->fetch();
        }
    }

    /**
     * 录入小程序发货信息
     */
    public function uploadWxappShippingInfo($openid, $order_data)
    {
        $data = array(
//            'access_token'=> getAccessToken(),
            'order_key' => array(
                'order_number_type' => 2,
                'transaction_id' => $order_data['transaction_id'],//微信支付返回id
            ),
            'logistics_type' => 1,//物流模式，发货方式枚举值：1、实体物流配送采用快递公司进行实体物流配送形式 2、同城配送 3、虚拟商品，虚拟商品，例如话费充值，点卡等，无实体配送形式 4、用户自提
            'delivery_mode' => 1,//发货模式，发货模式枚举值：1、UNIFIED_DELIVERY（统一发货）2、SPLIT_DELIVERY（分拆发货） 示例值: UNIFIED_DELIVERY
            'shipping_list' => array(
                array(
                    'tracking_no' => $order_data['express_no'],//物流单号
                    'express_company'=>$order_data['express_id'],//物流公司编码
//                    'express_company' => 'STO',//物流公司编码
//                    'item_desc'=>$order_data['product_desc'],//商品信息：商品名称*数量
                    'item_desc' => '康必安',//商品信息：商品名称*数量
//                    'contact'=>array(
//                        'consignor_contact'=> mb_substr($order_data['order_contact'], 0, 3, 'utf-8').'****'. mb_substr($order_data['order_contact'], -4, 4, 'utf-8'),//联系方式，当发货的物流公司为顺丰时，联系方式为必填，收件人或寄件人联系方式二选一，示例值：189****1234
//                    )
                )
            ),
            'upload_time' => date('c'),//输出值：2022-12-15T13:29:35+08:00
            'payer' => array(
                'openid' => $openid,
            )
        );

        $url = 'https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token=' . getAccessToken();
        $res = request_post($url, $data);
        return $res;
    }

    /**
     * 商户信息删除
     * @return [type] [description]
     */
    public
    function delete()
    {
        if ($this->request->isAjax()) {
            $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
            if (false == Db::name('shop')->where('id', $id)->delete()) {
                return $this->error('删除失败');
            } else {
//                addlog($id);//写入日志
                return $this->success('删除成功', 'admin/shop/index');
            }
        }
    }

    public
    function status()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            if (false == Db::name('shop')->where('id', $post['id'])->update(['status' => $post['status']])) {
                return $this->error('设置失败');
            } else {
//                addlog($post['id']);//写入日志
                return $this->success('设置成功', 'admin/shop/index');
            }
        }
    }
}
